<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<div id="appUser">
<el-row>
<el-col :span="24">
	<el-breadcrumb separator-class="el-icon-arrow-right">
		<el-breadcrumb-item>首页</el-breadcrumb-item>
		<el-breadcrumb-item>用户与权限</el-breadcrumb-item>
		<el-breadcrumb-item>用户管理</el-breadcrumb-item>
	</el-breadcrumb>
</el-col>
</el-row>
<el-row>
<el-col :span="24"align="right">
	<el-button @click="clearFilter" size="small">清除所有筛选<i class="el-icon-close el-icon--right"></i></el-button>
	<el-button @click="handleAddUser" size="small" type="success" icon="el-icon-circle-plus-outline">添加用户</el-button>
</el-col>
</el-row>
<br>
<el-row>
<el-col :span="24">
	<el-table ref="tableUser" :data="tableUserData" border stripe fit highlight-current-row
		v-loading="tableUserLoading" max-height="1200">
	    <el-table-column type="index" label="序号" :index="indexMethod" width="80">
	    </el-table-column>
		<el-table-column prop="username" label="用户名" width="120">
		</el-table-column>
		<el-table-column prop="phone" label="手机号码" width="120">
		</el-table-column>
		<el-table-column prop="email" label="Email" width="240">
		</el-table-column>
		<el-table-column prop="created" label="创建日期" :formatter="dateFormat" width="180" sortable>
		</el-table-column>
		<el-table-column prop="updated" label="修改日期" :formatter="dateFormat" width="180" sortable>
		</el-table-column>
		<el-table-column prop="status" label="状态" width="80"
	      :filters="[{ text: '正常', value: 1 }, { text: '禁用', value: 2 }]"
	      :filter-method="filterStatus"
	      filter-placement="bottom-end">
	      <template slot-scope="scope">
	        <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" size="small"
	          disable-transitions>{{scope.row.status === 1 ? '正常' : '禁用'}}</el-tag>
	      </template>
		</el-table-column>
	    <el-table-column label="操作" width="180">
			<template slot-scope="scope">
				<el-button @click="handleEditUser(scope.$index, scope.row)" type="text" size="small">编辑</el-button>
				<el-button @click="handleResetPwd(scope.$index, scope.row)" type="text" size="small">重置密码</el-button>
				<el-button @click="handleSetRole(scope.$index, scope.row)" type="text" size="small">指定角色</el-button>
			</template>
	    </el-table-column>
	</el-table>
</el-col>
</el-row>
<el-row>
<el-col :span="24">
	<el-pagination
		@size-change="handleSizeChange"
		@current-change="handleCurrentChange"
		:current-page="page"
		:page-sizes="[1, 10, 20, 50, 100]"
		:page-size="20"
		layout="total, sizes, prev, pager, next, jumper"
		:total="total">
	</el-pagination>
</el-col>
</el-row>

<el-dialog :title="dialogUserTitle" :visible.sync="dialogUserVisible" width="600px" @closed="dialogUserClosed">
	<el-form ref="formUser" :model="modelUser" status-icon :rules="rulesUser">
		<el-form-item label="用户名" :label-width="formUserLabelWidth" prop="username">
			<el-input v-model="modelUser.username" autocomplete="off" maxlength="50"></el-input>
		</el-form-item>
		<el-form-item label="手机号" :label-width="formUserLabelWidth" prop="phone">
			<el-input v-model="modelUser.phone" autocomplete="off" maxlength="20"></el-input>
		</el-form-item>
		<el-form-item label="Email" :label-width="formUserLabelWidth" prop="email">
			<el-input v-model="modelUser.email" autocomplete="off" maxlength="50"></el-input>
		</el-form-item>
		<el-form-item label="状态" :label-width="formUserLabelWidth">
			<el-select v-model="modelUser.status" placeholder="请选择状态">
				<el-option v-for="option in statusOptions" :key="option.value" :label="option.label" :value="option.value"></el-option>
			</el-select>
		</el-form-item>
	</el-form>
	<div slot="footer" class="dialog-footer">
		<el-button @click="dialogUserVisible = false">取 消</el-button>
		<el-button type="primary" :loading="isButtonLoadingUser" @click="onSubmitUser">确 定</el-button>
	</div>
</el-dialog>

<el-dialog :title="dialogSetRoleTitle" :visible.sync="dialogSetRoleVisible" width="600px" @closed="dialogSetRoleClosed">
	<el-transfer v-model="valueSetRole" :data="dataSetRole" :titles="titlesSetRole"></el-transfer>
	<div slot="footer" class="dialog-footer">
		<el-button @click="dialogSetRoleVisible = false">取 消</el-button>
		<el-button type="primary" :loading="isButtonLoadingSetRole" @click="onSubmitSetRole">确 定</el-button>
	</div>
</el-dialog>
</div>

<script>
	var appUser = new Vue({
		el: '#appUser',
		data() {
			var checkUsername = (rule, value, callback) => {
		        if (!value) {
		          return callback(new Error('用户名不能为空'));
		        } else {
		        	callback();
		        }
			};
			var checkPhone = (rule, value, callback) => {
		        if (!value) {
		          return callback(new Error('手机号不能为空'));
		        } else {
		        	callback();
		        }
			};
			var checkEmail = (rule, value, callback) => {
		        if (!value) {
		          return callback(new Error('Email不能为空'));
		        } else {
		        	callback();
		        }
			};
			return {
				urlPostUserList: '/api/user/list',
				urlPostUserSave: '/api/user/save',
				urlGetResetPwd: '/api/user/resetpwd/',
				urlPostRoleList: '/api/role/list',
				urlGetUserRole: '/api/user/role/',
				urlPostSetRole: '/api/user/setrole',
				page: 1,
				rows: 20,
				total: 100,
				tableUserData: [],
				tableUserLoading: false,
				dialogUserVisible: false,
				dialogUserTitle: '添加用户',
				statusOptions: [{
					label: '正常', value: 1
				},{
					label: '禁用', value: 2
				}],
				modelUser: {
					id: null,
		            username: '',
		            phone: '',
		            email: '',
		            status: 1
		          },
				rulesUser: {
					username: [{validator: checkUsername, trigger: 'blur'}],
					phone: [{validator: checkPhone, trigger: 'blur'}],
					email: [{validator: checkEmail, trigger: 'blur'}]
				},
				formUserLabelWidth: '60px',
				isButtonLoadingUser: false,
				dataSetRole: [],
				valueSetRole: [],
				userIdSetRole: null,
				dialogSetRoleTitle: '指定角色',
				dialogSetRoleVisible: false,
				isButtonLoadingSetRole: false,
				titlesSetRole: ['未指定角色', '已指定角色']				
			}
		},
		methods: {
			/* Table */
			loadTableUserData() {
				this.tableUserLoading = true;
				this.$http.post(this.urlPostUserList, {page: this.page, rows: this.rows}, {emulateJSON: true}).
				then(function(response) {
					if (response.body.status == 200) {
						this.tableUserData = response.body.data.list;
						this.total = response.body.data.total;
						this.tableUserLoading = false;
					}
				}).catch(function (error) {
					console.log(error);
				});	
			},
			handleSizeChange(val) {
				console.log('每页' + val + '条');
				this.rows = val;
				this.loadTableUserData();
			},
			handleCurrentChange(val) {
				console.log('当前页:' + val);
				this.page = val;
				this.loadTableUserData();
			},
			handleAddUser() {
				this.dialogUserTitle = '添加用户';
				this.dialogUserVisible = true;
			},
			handleEditUser(index, row) {
				console.log(index, row);
				//this.$message(row.id + '');
				this.dialogUserTitle = '修改用户';
				this.dialogUserVisible = true;
				this.modelUser.id = row.id;
				this.modelUser.username = row.username;
				this.modelUser.phone = row.phone;
				this.modelUser.email = row.email;
				this.modelUser.status = row.status;
			},
			handleResetPwd(index, row) {
				this.$confirm('确认要重置用户【' + row.username + '】的密码?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$http.get(this.urlGetResetPwd + row.id).then(function(response) {
						if (response.body.status == 200) {
							this.$message({
								message: "重置成功",
								type: "success"
							});
						}
	    			}).catch(function (error) {
						console.log(error);
					});	
				}).catch(() => {         
				});			
			},
			indexMethod(index) {
				return index + 1;
			},
			dateFormat(row, column, cellValue, index) {
				var date = new Date(cellValue);
				return formatDate(date, "yyyy-MM-dd hh:mm:ss");
			},
			filterStatus(value, row) {
				return row.status === value;
			},
			clearFilter() {
				this.$refs.tableUser.clearFilter();
			},
			/* Edit */
			onSubmitUser() {
				this.isButtonLoadingUser = true;
				this.$refs.formUser.validate((valid) => {
					if (valid) {
						this.$refs.formUser.$http.post(this.urlPostUserSave, this.modelUser, {emulateJSON: true})
						.then(function (response) {
							if (response.body.status == 200) {
								this.$message({
									message: "保存成功",
									type: "success"
								});
								appUser.isButtonLoadingUser = false;
								appUser.dialogUserVisible = false;								
								appUser.loadTableUserData();
							} else {
								this.$message.error(response.body.msg);
								appUser.isButtonLoadingUser = false;
							}
						}).catch(function (error) {
							console.log(error);
						});							
					}
				});
			},
			resetForm() {
				this.modelUser = {
						id: null,
			            username: '',
			            phone: '',
			            email: '',
			            status: 1
				};
				this.$refs.formUser.resetFields();
			},
			dialogUserClosed() {
				this.resetForm();
			},
			/* Role */
			dialogSetRoleClosed() {
				this.valueSetRole = [];
			},
			handleSetRole(index, row) {
				this.dialogSetRoleTitle = '为用户【' + row.username + '】指定角色';
				this.userIdSetRole = row.id;
				this.$http.get(this.urlGetUserRole + row.id).then(function(response) {
					if (response.body.status == 200) {
						this.dialogSetRoleVisible = true;
						this.valueSetRole = response.body.data;
					}
    			}).catch(function (error) {
					console.log(error);
				});	
			},
			onSubmitSetRole() {			
				this.isButtonLoadingSetRole = true;
				this.$http.post(this.urlPostSetRole, {userId: this.userIdSetRole, roleIds: this.valueSetRole.join(',')}, {emulateJSON: true})
				.then(function (response) {
					if (response.body.status == 200) {
						this.isButtonLoadingSetRole = false;
						this.dialogSetRoleVisible = false;
					} else {
						this.$message.error(response.body.msg);
					}
				}).catch(function (error) {
					console.log(error);
				});
			},
			loadDataSetRole() {				
				this.$http.post(this.urlPostRoleList, null, {emulateJSON: true})
				.then(function (response) {
					if (response.body.status == 200) {
						var array = new Array();
						response.body.data.list.forEach(function(item, index) {
							array.push({key: item.id, label: item.name});
						});
						this.dataSetRole = array;
					} else {
						this.$message.error(response.body.msg);
					}
				}).catch(function (error) {
					console.log(error);
				});
			}
		},
		created() {
			this.loadTableUserData();
			this.loadDataSetRole();
		}
	})
</script>